package com.example.administrator.k3xiangmu;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import net.sourceforge.jtds.jdbc.Driver;

import com.android.barcodescandemo.ScannerInerface;
import com.example.administrator.k3xiangmu.adapter.PDAdapter;
import com.example.administrator.k3xiangmu.adapter.RukuAdapter;
import com.example.administrator.k3xiangmu.entity.FSN;
import com.example.administrator.k3xiangmu.entity.KH;
import com.example.administrator.k3xiangmu.entity.PDEntity;
import com.example.administrator.k3xiangmu.entity.RukuEntity;
import com.example.administrator.k3xiangmu.entity.SubPD;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PDActivity extends AppCompatActivity {
    private Toolbar toolbar;
    ProgressDialog dialog;
    private BroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    ScannerInerface Controll = new ScannerInerface(this);
    ExpandableListView lv;
    PDAdapter adapter;
    private List<PDEntity> pdEntityList = new ArrayList<>();
    private String fsn;
    private Button tj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pd);
        Controll.open();
        Controll.setOutputMode(1);//使用广播模式
        mFilter = new IntentFilter("android.intent.action.SCANRESULT");
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 此处获取扫描结果信息
                final String scanResult = intent.getStringExtra("value");
                Toast.makeText(PDActivity.this, "解析结果:" + scanResult, Toast.LENGTH_LONG).show();
                String[] s = scanResult.split("\\[");
                if (s.length == 2) {
                    fsn = s[1];
                    for (PDEntity p : pdEntityList) {
                        if (p.getFsn().equals(fsn)) {
                            Toast.makeText(PDActivity.this, "该物料已盘点", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                    getData();
                } else {
                    Toast.makeText(PDActivity.this, "二维码错误:" + scanResult, Toast.LENGTH_LONG).show();
                }


            }
        };

        dialog = new ProgressDialog(this);

        setTool();
        setView();
        setListen();
    }
    private void setListen(){
        tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(pdEntityList.size()==0){
                    Toast.makeText(PDActivity.this, "盘点数量不能为0" , Toast.LENGTH_LONG).show();
                }
                UpdateTextTask3 updateTextTask = new UpdateTextTask3(PDActivity.this);
                updateTextTask.execute();
            }
        });
    }
    private void setView() {
        tj = (Button) findViewById(R.id.tj);
        lv = (ExpandableListView) findViewById(R.id.lv);
        //lv.setChildDivider(new BitmapDrawable()); expView.setGroupIndicator(null);
      lv.setDividerHeight(0);
        lv.setGroupIndicator(null);
        adapter = new PDAdapter(pdEntityList, this);
        lv.setAdapter(adapter);


    }

    private void setTool() {
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle("盘点单");

        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);


        toolbar.setNavigationIcon(android.R.drawable.ic_menu_revert);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String msg = "";
                switch (item.getItemId()) {
                    case R.id.action_sm:
                        msg += "Click edit";
                        break;

                }

                if (!msg.equals("")) {
                    Toast.makeText(PDActivity.this, msg, Toast.LENGTH_SHORT).show();
                    if (Build.VERSION.SDK_INT > 22) {
                        if (ContextCompat.checkSelfPermission(PDActivity.this,
                                android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                            //先判断有没有权限 ，没有就在这里进行权限的申请
                            ActivityCompat.requestPermissions(PDActivity.this,
                                    new String[]{android.Manifest.permission.CAMERA}, 1);

                        } else {
                            //说明已经获取到摄像头权限了 想干嘛干嘛
                            Intent intent = new Intent(PDActivity.this, CaptureActivity.class);
                            startActivityForResult(intent, 111);
                        }
                    } else {
//这个说明系统版本在6.0之下，不需要动态获取权限。

                    }


                }
                return true;

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);//加载menu文件到布局
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 111) {
            //处理扫描结果（在界面上显示）

            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                    String[] s = result.split("\\[");
                    if (s.length == 2) {
                        fsn = s[1];
                        for (PDEntity p : pdEntityList) {
                            if (p.getFsn().equals(fsn)) {
                                Toast.makeText(PDActivity.this, "该物料已盘点", Toast.LENGTH_LONG).show();

                                return;
                            }
                        }
                        getData();
                    } else {
                        Toast.makeText(PDActivity.this, "二维码错误:" + result, Toast.LENGTH_LONG).show();
                    }


                    //number = result;


                }
            }
        }
    }

    private void getData() {
        UpdateTextTask2 updateTextTask = new UpdateTextTask2(this);
        updateTextTask.execute();
    }

    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();

             adapter.notifyDataSetChanged();
           // adapter.notifyAll();

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {

            String sql = "SELECT a.* ,b.*,c.FName,c.FItemID  FROM dbo.z_xlh_zulin a INNER JOIN dbo.z_xlh_xq b ON a.FSN=b.FSN INNER JOIN dbo.t_ICItem c ON a.FNumber=c.FNumber WHERE a.FSN='" + fsn + "'";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor

            PDEntity p = new PDEntity();
            List<SubPD> subPDList = new ArrayList<>();

            while (rs.next()) {
                int i = 0;

                if (i == 0) {
                    p.setTime(rs.getString("time"));
                    p.setFsn(rs.getString("fsn"));
                    p.setFbase(rs.getInt("fitemid"));
                    p.setStatus(rs.getString("status"));
                    p.setName(rs.getString("fname"));
                    p.setFnumber(rs.getString("fnumber"));
                    p.setWz(rs.getString("weizhi"));
                    p.setFuser(rs.getString("fuser"));
                    p.setDate(rs.getDate("fdate"));
                }
                SubPD pd=new SubPD();
                pd.setStatus(rs.getString("status"));
                pd.setTime(rs.getString("time"));

                subPDList.add(pd);

            }
            p.setSubPDList(subPDList);
            pdEntityList.add(p);

            rs.close();
            stmt.close();
        } catch (SQLException e) {


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
    class UpdateTextTask3 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask3(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection3(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();
            pdEntityList.clear();
            adapter.notifyDataSetChanged();
            Toast.makeText(PDActivity.this, "提交成功", Toast.LENGTH_LONG).show();
            // adapter.notifyAll();

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
    public void testConnection3(Connection con) throws java.sql.SQLException {
        CallableStatement stmt = con.prepareCall("{call [z_pdhead] (?)}");// 创建Statement
        CallableStatement statement2=con.prepareCall("{call [z_pden](?,?,?,?,?,?) }");
        try {

            stmt.setString(1,pdEntityList.get(0).getFuser());

            stmt.execute();


            int i=0;
            for(PDEntity e:pdEntityList){
                i++;
                statement2.setInt(1,i);
                statement2.setInt(2,e.getFbase());
                statement2.setString(3,e.getFsn());
                statement2.setString(4,e.getBz());
                Log.i("eee",e.getDate()+"ssss");
                statement2.setDate(5,e.getDate());

                statement2.setString(6,e.getWz());
                statement2.execute();
            }

            // ResultSet类似Cursor








        } catch (SQLException e) {
            Log.e("eee",e.toString());

        } finally {
            stmt.close();
            statement2.close();

            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
}
